package ru.hh.team02.chat.client;

import org.junit.Test;
import ru.hh.team02.chat.database.DbStub;
import ru.hh.team02.chat.server.Services;

import java.util.ArrayList;

import static org.junit.Assert.assertEquals;

public class ClientRegistryConcurrencyTestNonDeterministic {
    private String[] getRoomNames(String[][] data) {
        String[] roomNames = new String[data.length];
        for (int i = 0; i < data.length; i++) {
            roomNames[i] = data[i][1];
        }
        return roomNames;
    }

    @Test
    public void shoudHaveAppropriateClientsCountOnAddingClientsFromMultipleThreads() {
        final int clientCountPerThread = 1000;
        final int threadsCount = 100;
        
        String[] roomNames = { "room1" };

        final ClientRegistry clientRegistry = new ClientRegistry(roomNames);

        final ArrayList<Client> clients =
                new ArrayList<Client>();

        String [][] data = new String [clientCountPerThread][];

        for (int i = 0; i < clientCountPerThread; ++i) {
            clients.add(new Client("client" + i));
            data[i] = new String [] {"client" + i, "room1"};
        }




        Services.dbService = new DbStub(data);
        
        for (int i = 0; i < threadsCount; ++i) {
            new Thread() {
                @Override
                public void run() {
                    for (int j = 0; j < clientCountPerThread; ++j) {
                        clientRegistry.addClient(clients.get(j),"room1");
                    }
                }
            }.start();    
        }
        
        
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
 
        assertEquals(clientCountPerThread, clientRegistry.getClientsFromRoom("room1").size());

    }

}
